package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.Moments;
import com.web.exiaodao.business.repository.MomentsRepository;
import com.web.exiaodao.business.service.MomentsService;

@Service("MomentsService")
@Transactional(readOnly = false)
public class MomentsServiceImpl extends BaseService<Moments> implements MomentsService {

	private static final Logger LOGGER = Logger.getLogger(MomentsServiceImpl.class);

	@Autowired
	private MomentsRepository momentsRepository;
	
	/**
	 * 查询单条Moments信息
	 * //@param tId
	 * @return 返回单个Moments对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Moments> findOne(Long modelId) throws BusinessException {
		Moments obj = new Moments();
		if(modelId != 0){
			obj = momentsRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<Moments> xr = new XaResult<Moments>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->Moments");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的Moments数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Moments集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<Moments>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<Moments> page = momentsRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Moments.class), pageable);
		XaResult<Page<Moments>> xr = new XaResult<Page<Moments>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->Moments");
		return xr;
	}

	/**
	 * 分页查询状态status的Moments数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Moments集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<Moments>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<Moments> page = momentsRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Moments.class), pageable);
		XaResult<Page<Moments>> xr = new XaResult<Page<Moments>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->Moments");
		return xr;
	}

	/**
	 * 保存Moments信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Moments> saveOrUpdate(Moments model) throws BusinessException {
		Moments obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = momentsRepository.findOne(model.getId());
		}else{
			obj = new Moments();
		}
	    obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
	    obj.setContent(XaUtil.isNotEmpty(model.getContent()) ? model.getContent() : obj.getContent());
	    obj.setPhotos(XaUtil.isNotEmpty(model.getPhotos()) ? model.getPhotos() : obj.getPhotos());
		obj = momentsRepository.save(obj);
		XaResult<Moments> xr = new XaResult<Moments>();
		xr.setObject(obj);
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改Moments状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回Moments对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Moments> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<Moments> xr = new XaResult<Moments>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				Moments obj = momentsRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = momentsRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	/**
	 * 朋友圈查询，分页，用户名查询
	 */
	@Override
	public XaResult<Page<Moments>> findMomentskList(Integer nextPage, Integer pageSize,
			Map<String, Object> filterParams) throws BusinessException {
		//select f.id, f.content,f.photos,u.user_name,f.create_time from tb_xa_moments f left join tb_xa_user u on u.id = f.user_id where f.`status`<>3
		StringBuffer sql=new StringBuffer("select f.id, f.content,f.photos,u.user_name,f.create_time ");
		sql.append("from tb_xa_moments f left join tb_xa_user u on u.id = f.user_id ");
		sql.append(" WHERE f.STATUS<> ").append(XaConstant.Status.delete);
		//统计数据库中数据个数
		StringBuffer sql1=new StringBuffer("select count(*) ");
		sql1.append("from tb_xa_moments f left join tb_xa_user u on u.id = f.user_id ");
		sql1.append(" WHERE f.STATUS<> ").append(XaConstant.Status.delete);
		//查询条件
				
				//用户名
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_userName"))){
					sql.append(" AND u.user_name ").append(" like '%").append(filterParams.get("LIKE_userName")).append("%' ");
					sql1.append(" AND u.user_name ").append(" like '%").append(filterParams.get("LIKE_userName")).append("%' ");
				}
				//朋友圈内容
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_content"))){
					sql.append(" AND f.content ").append(" like '%").append(filterParams.get("LIKE_content")).append("%' ");
					sql1.append(" AND f.content ").append(" like '%").append(filterParams.get("LIKE_content")).append("%' ");
				}
				
				sql.append(" ORDER BY f.create_time DESC");
				sql1.append(" ORDER BY f.create_time DESC");
				List<Object[]> objs=this.query(sql.toString(), nextPage*pageSize, pageSize);
				List<Moments> vos=new ArrayList<Moments>();
				
				for (Object[] obj : objs) {	
					Moments vo = new Moments();
					vo.setId(Long.valueOf(obj[0].toString()));
					vo.setContent(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
					vo.setPhotos(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
					vo.setUserName(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
					vo.setCreateTime(XaUtil.isEmpty(obj[4])?"":obj[4].toString());
					vos.add(vo);
				}
				//执行查询语句
				List<Object[]> obj1=this.query(sql1.toString(), null, null);
				//将得到的查询结果强转成int类型
				int count=Integer.parseInt(obj1.get(0)+"");				
				//调用分页
				Page<Moments> page= new MyPage<Moments>(nextPage.intValue(),pageSize.intValue(),vos,count);
				//创建结果集对象xr
				XaResult<Page<Moments>> xr=new XaResult<Page<Moments>>();
				//将page放入xr
				xr.setObject(page);
				return xr;
	}

	/**
	 * 根据朋友圈ID查找好友或者其他人对朋友圈评论或点赞详情
	 */
	@Override
	public List<Moments> findMomentsInteractionsByMomentsId(Long momentsId) throws BusinessException {
		//select f.id, f.content,f.photos,u.user_name ,mf.content,u1.user_name as reply_username ,mf.type,u2.user_name as m_user_name
		//from tb_xa_moments f 
		//left join tb_xa_momentsinteraction mf on f.id=mf.moment_id 
		//left join tb_xa_user u on u.id = f.user_id 
		//left join tb_xa_user u1 on u1.id = mf.reply_to_user_id 
		//left join tb_xa_user u2 on u2.id = mf.user_id 
		//where f.`status`<>3
		StringBuffer sql=new StringBuffer("select f.id, f.content as c1,f.photos,u.user_name as m1 ,mf.content as c2,u1.user_name as m2 ,mf.type,u2.user_name as m3 ");
		sql.append("from tb_xa_moments f  ");
		sql.append("left join tb_xa_momentsinteraction mf on f.id=mf.moment_id ");
		sql.append("left join tb_xa_user u on u.id = f.user_id ");
		sql.append("left join tb_xa_user u1 on u1.id = mf.reply_to_user_id ");
		sql.append("left join tb_xa_user u2 on u2.id = mf.user_id ");
		sql.append("WHERE f.id=").append(momentsId).append(" ");
		sql.append("AND f.STATUS<> ").append(XaConstant.Status.delete);
		List<Object[]> objs=this.query(sql.toString(), null, null);
		List<Moments> vos=new ArrayList<Moments>();
		
		for (Object[] obj : objs) {	
			Moments vo = new Moments();
			vo.setId(Long.valueOf(obj[0].toString()));
			vo.setContent(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			vo.setPhotos(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setUserName(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
			vo.setReplyContent(XaUtil.isEmpty(obj[4])?"":obj[4].toString());
			vo.setReplyToUserName(XaUtil.isEmpty(obj[5])?"":obj[5].toString());
			vo.setType((Integer) (XaUtil.isEmpty(obj[6])?"":Integer.valueOf(obj[6].toString())));
			vo.setmUserName(XaUtil.isEmpty(obj[7])?"":obj[7].toString());
			vos.add(vo);
		}
		
		return  vos;
		
	}
	
}
